package cn.calm.datasource.provider;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.spi.ObjectFactory;
import javax.sql.DataSource;

import org.apache.naming.ResourceRef;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.cloudfoundry.runtime.env.CloudEnvironment;
import org.cloudfoundry.runtime.env.RdbmsServiceInfo;

//import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;

public class DataSourceFactory implements ObjectFactory {

	@Override
	public Object getObjectInstance(Object obj, Name name, Context nameCtx,
			Hashtable<?, ?> environment) throws Exception {
		if (obj != null) {
			String url = null;
			String username = null;
			String password = null;
			String driverClass;
			ResourceRef ref = (ResourceRef) obj;
			Object serviceName = ref.get("serviceName").getContent();
			driverClass = ref.get("driverClassName").getContent().toString();
			if (serviceName != null) {
				String service = serviceName.toString();
				CloudEnvironment ce = new CloudEnvironment();
				try{
					RdbmsServiceInfo info = ce.getServiceInfo(service,
							RdbmsServiceInfo.class);
					url=info.getUrl();
					username=info.getUserName();
					password=info.getPassword();
				}catch(Exception e){
					url = ref.get("url").getContent().toString();
					username = ref.get("username").getContent().toString();
					password = ref.get("password").getContent().toString();
				}
			} else {
				url = ref.get("url").getContent().toString();
				username = ref.get("username").getContent().toString();
				password = ref.get("password").getContent().toString();
			}
			return buildDataSource(url, username, password, driverClass);
		}
		return null;
	}

	public DataSource buildDataSource(String url, String username,
			String password, String driverClass) {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		dataSource.setDriverClassName(driverClass);
		return dataSource;
	}
}
